package servlet;

import dao.ArticleDao;
import dao.LabelDao;
import dao.daoimpl.ArticleDaoImpl;
import dao.daoimpl.LabelDaoImpl;
import bean.Article;
import bean.Label;
import bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

@WebServlet(name = "UpdateBlogServlet",urlPatterns = "/UpdateBlogServlet")
public class UpdateBlogServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");/*防止乱码*/
        User user=(User)request.getSession().getAttribute("user");
        ArrayList<Label> labels=(ArrayList<Label>)request.getSession().getAttribute("userLabels");
        String [] label=request.getParameterValues("updateArticleLabels");/*获取文章标签*/
        String time=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());/*获取当前时间*/
        int articleId=Integer.parseInt(request.getParameter("updateArticleId"));/*获取id*/
        ArrayList<Label> labels1=new ArrayList<>();
        for(int j=0;j<label.length;j++){
            for(int i=0;i<labels.size();i++){
                if(label[j].equals(labels.get(i).getContent())){
                    labels1.add(labels.get(i));
                }
            }
        }
        int category=Integer.parseInt(request.getParameter("updateArticleCategory"));/*获取文章目录*/
        String subfield=request.getParameter("updateArticleSubfield");/*获取文章分栏*/
        String type= request.getParameter("updateArticleType");/*获取文章类型*/
        String content = request.getParameter("updateArticleContent");/*获取文章内容*/
        String title=request.getParameter("updateArticleTitle");/*获取文章标题*/
        int approve=0;/*未过审*/
        ArticleDao articleDao=new ArticleDaoImpl();/*文章接口的操作类*/
        LabelDao labelDao=new LabelDaoImpl();
        Article article=new Article(articleId,content,title,time,category,labels1,type,subfield,approve);
        try {
            if(articleDao.updateArticle(article)&&labelDao.deleteArticleLabel(articleId)&&labelDao.addLabel(labels1,articleId)){/*修改成功*/
                System.out.println("用户博客修改成功");
                request.getSession().setAttribute("userArticles",articleDao.getArticles(user));/*返回集合*/
            }else{
                System.out.println("用户博客修改失败");
            }
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }

    }
}
